<!--
 * @Descripttion:
 * @Author: yuhaonan
 * @Date: 2021-04-05 19:16:43
 * @LastEditors: zhengminjie
 * @LastEditTime: 2021-07-04 17:21:14
-->
<template>
  <div class="app-container">
    <el-form :label-position="labelPosition" :model="documentManager" ref="excelForm" v-show="showSearch" @submit.native.prevent :inline="true">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="documentManager.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="getList"
        />
      </el-form-item>
      <el-form-item>
        <el-col :span="1.5">
          <el-button 
            type="primary" 
            plain
            size="small"
            icon="el-icon-search"
            @click="getList"
          >搜索</el-button>
        </el-col>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="small"
          icon="el-icon-circle-plus-outline"
          @click="addProject = true"
          >新建项目
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="small"
          icon="el-icon-upload"
          @click="documentUpload = true"
          >上传文件
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="small"
          icon="el-icon-share"
          @click="DocumentSend()"
          :disabled="single"
          >分发文件
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column	type="selection"  width="55" align="center" />
      <el-table-column  prop="projectId" label="项目id" v-if="false"/>
      <el-table-column  prop="projectName"	label="项目名称"  align="center" :show-overflow-tooltip="true" />
      <el-table-column  prop="projectSummary"	label="项目摘要"  align="center" :show-overflow-tooltip="true" />
      <el-table-column  label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="checkView(scope.row,scope.$index)"
          >详细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            style="color:red"
            :disabled="projectDisabled[scope.$index]"
            @click="deleted(scope.row,scope)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建项目对话框 -->
    <el-dialog title="新建项目" :visible.sync="addProject" width="400px" center>
      <el-form :model="addForm" ref="addForm" :rules="ruleAdd">
        <el-form-item label="设置项目名称" prop="projectName">
          <el-input v-model="addForm.projectName" style="width:200px" placeholder="输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="设置项目摘要" prop="projectSummary">
          <el-input v-model="addForm.projectSummary" type="textarea" style="width:200px" placeholder="输入项目摘要"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="AddProject('addForm')">创 建</el-button>
        <el-button @click="addProject = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分发文件对话框 -->
    <el-dialog title="分发文件" :visible.sync="documentSend" width="750px">
        <el-form ref="sendForm" :model="sendForm">
          <el-form-item>
            <el-transfer 
              v-model="sendForm.choiceData" 
              :titles="['所有文件名','分发文件名']" 
              :button-texts="['到左边', '到右边']" 
              :data="sendForm.dataList"
            ></el-transfer>
          </el-form-item>
          <el-form-item label="所有人可见数据还是只能见自己数据">
            <el-radio-group v-model="sendForm.resource">
              <el-radio label="所有人可见"></el-radio>
              <el-radio label="仅自己可见"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择分发群组">
            <el-select v-model="sendForm.groupList" placeholder="选择要分发的群组">
              <el-option
                v-for="item in groupList"
                :key="item.groupId"
                :label="item.groupName"
                :value="item.groupId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="documentSend = false">取 消</el-button>
          <el-button type="primary" @click="sendSubmit(sendForm)">确 定</el-button>
        </span>
      </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog title="上传文件" :visible.sync="documentUpload" width="40%">
        <div style="text-align:center;padding-bottom:10px">
        <el-input
          v-model="upload.col"
          placeholder="请输入目录名"
          clearable
          style="width:240px"
        />
        </div>
        <center>
          <el-upload
            ref="upload"
            :limit="100"
            accept=".doc, .docx"
            :action="upload.url"
            :data="upload.paramsData"
            :http-request="uploadFile"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            drag
            multiple
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button><br>
            <el-button size="small" type="success" :disabled="!upload.col" :loading="upload.isUploading" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传docx/doc文档，且不超过500kb，一次最多能上传100个文档<br><span style="color:red">每份文档名要与用户身份编号对应才能正确分发</span></div>
          </el-upload>
        </center>
      </el-dialog>

<!-- 详情对话框 -->
  <el-dialog title="项目详情" :visible.sync="openView" width="500px">
    <el-form ref="viewForm" :model="viewForm" label-width="120px" :inline="true">
      <el-form-item label="项目名称">
        <el-input v-model="viewForm.name" disabled style="width:240px"></el-input>
      </el-form-item>
      <el-form-item label="项目摘要">
        <el-input v-model="viewForm.summary" disabled style="width:240px"></el-input>
      </el-form-item>
      <el-form-item label="选择分发文档名">
        <el-select v-model="viewForm.documentList" placeholder="选择已分发的表格" @change="checkChange">
          <el-option
            v-for="item in documentList"
            :key="item.officeId"
            :label="item.officeName"
            :value="item.officeId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分发人数">
        <el-input v-model="viewForm.send" disabled style="width:60px"></el-input>
      </el-form-item>
      <el-form-item label="未读人数">
        <el-input v-model="viewForm.unRead" disabled style="width:60px"></el-input>
      </el-form-item>
      <el-form-item label="同意人数">
        <el-input v-model="viewForm.agree" disabled style="width:60px"></el-input>
      </el-form-item>
      <el-form-item label="拒绝人数">
        <el-input v-model="viewForm.refuse" disabled style="width:60px"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="openView = false">取 消</el-button>
      <el-button type="primary" @click="openView = false">确 定</el-button>
    </span>
  </el-dialog>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="documentManager.pageNum"
      :limit.sync="documentManager.pageSize"
    />
  </div>
</template>


<script>
import {AddProject, searchProject, uploadWord, documentList, getGroupList, sendDocument, checkDocument, Change} from '@/api/distribution/documentManager';
import { getToken } from "@/utils/auth";

export default {
  name: "DocumentManager",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中项目数组
      projectId: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //表格位置
      labelPosition:'left',
      // 表格数据
      projectList: [],
      // 新建项目
      addProject: false,
      addForm:{
        projectName:'',
        projectSummary:'',
      },
      ruleAdd:{
        projectName:[
          { required: true, message: '请填写项目名称', trigger: 'blur' }
        ],
          projectSummary:[
          { required: true, message: '请填写项目摘要', trigger: 'blur' }
        ]
      },
      // 分发文档
      documentSend:false,
      sendForm:{
        dataList:[],
        choiceData:[],
        resource:'仅自己可见',
        groupList:'',
      },
      groupList:[],
       // 项目详情
      openView:false,
      viewForm:{
        name:'',
        summary:'',
        send:'',
        unRead:'',
        agree:'',
        refuse:'',
        documentList:'',
        projectId:'',
      },
      documentList:[],
      // 上传文档
      documentUpload:false,
      // 上传参数
      upload: {
        // 输入框
        col:'',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/distribution/documentManager/upload",
        // 上传的文件列表
        fileList: [],
        // 文件上传数据（多文件合一）
		    wordData: {},
        // 上传文件的数据
        paramsData: {
          office_name:''
        },
      },
      // 总条数
      total: 0,
      // 删除标记
      projectDisabled:[],
      //查询参数
      documentManager: {
        projectName: undefined,
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 刷新列表 */
    getList() {
      this.loading = true;
      this.projectDisabled = [];
      searchProject(this.documentManager).then(res=>{
        this.projectList = res.rows;
        console.log(this.projectList);
        res.rows.forEach(item=>{
          if(item.deleteFlag==2){
            this.projectDisabled.push(true);
          }
          else{
            this.projectDisabled.push(false);
          }
        })
        this.loading = false;
      })
    },
    // 新建项目
    AddProject(addForm){
      this.$refs[addForm].validate((valid) => {
        if (valid) {
          console.log(this.addForm);
          AddProject(this.addForm).then(res=>{
            this.$message.success('项目创建成功！');
            this.addProject = false;
            this.getList();
          })
        } else {
          this.$message.error('error submit!');
          return false;
        }
      });
    },
    /** 详细按钮操作 */
    checkView(row, index) {
      this.viewForm={
        name:'',
        summary:'',
        send:'',
        unRead:'',
        agree:'',
        refuse:'',
        documentList:'',
        projectId:'',
      },
      this.viewForm.name = row.projectName;
      this.viewForm.summary = row.projectSummary;
      this.viewForm.projectId = row.projectId;
      checkDocument(this.viewForm.projectId).then(res=>{
        this.documentList = res.rows;
      })
      this.openView = true;
    },
    checkChange(){
      console.log(this.viewForm);
      Change(this.viewForm.documentList,this.viewForm.projectId).then(res=>{
        this.viewForm.send = res.rows[0].send;
        this.viewForm.unRead = res.rows[0].unRead;
        this.viewForm.agree = res.rows[0].agree;
        this.viewForm.refuse = res.rows[0].refuse;
      })
    },
    /** 删除按钮 */
    deleted(row,index){
      console.log(index);
      this.$confirm('此操作将永久删除该项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       Delete(row.projectId).then(res=>{
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    /** 分发表格 */
    DocumentSend(){
      documentList().then(res=>{
        //console.log(res);
        this.sendForm.dataList = [];
        res.rows.forEach(item=>{
          this.sendForm.dataList.push({
            key:item.officeId,
            label:item.officeName
          });
        })
        this.documentSend = true;
      })
      getGroupList().then(res=>{
        //console.log(res);
        this.groupList = res.rows;
      })
    },
    sendSubmit(sendForm){
      console.log(sendForm);
      if(sendForm.choiceData.length == 0 || sendForm.groupList == ''){
        this.$message.error('要选择需分发的文档或分发的群组哟！');
      }
      else{
        let send = {};
        send.officeList = sendForm.choiceData;
        send.projectId = this.projectId[0];
        send.groupId = sendForm.groupList;
        if(sendForm.resource == "仅自己可见"){
          send.ifPublic = false;
        }
        else{
          send.ifPublic = true;
        }
        sendDocument(send).then(res=>{
          if(res.msg == "文件已分发"){
            this.$message.success('文件分发成功！');
          }
          this.documentSend = false;
        })
      }
    },
    // 文件提交处理
    submitUpload() {
      this.upload.wordData = new FormData()  //  用FormData存放上传文件
      this.$refs.upload.submit()  // 会循环调用uploadFile方法，多个文件调用多次
      this.upload.wordData.append('office_name', this.upload.col)
      uploadWord(this.upload.wordData).then((res) => {
          if (res.msg == "文件上传成功") {
            this.$message.success('文件上传成功!');
            this.fileList = [];
            this.documentUpload = false;
          }
      });
    },
    // 覆盖上传事件，选择文件之后触发的事件
    uploadFile(file) {
      this.upload.wordData.append('files', file.file);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.msgSuccess(response.msg);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.projectId = selection.map(item => item.projectId)
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
  }
};
</script>


